<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备标识" prop="deviceIdentification">
        <el-input
          v-model="queryParams.deviceIdentification"
          placeholder="请输入设备标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务名称" prop="serviceId">
        <el-select v-model="queryParams.serviceId" clearable placeholder="请选择服务名称" size="small" @change="changeService">
          <el-option v-for="dict in servicesList" :key="dict.id" :label="dict.serviceName" :value="dict.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="命令名称" prop="commandId">
        <el-select v-model="queryParams.commandId" clearable placeholder="请选择命令名称" size="small">
          <el-option v-for="dict in cdsList" :key="dict.id" :label="dict.name" :value="dict.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['iot:devicecommands:list']" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:devicecommands:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:devicecommands:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="commandsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="设备标识" align="center" prop="deviceIdentification" />
      <el-table-column label="服务名称" align="center" prop="serviceId">
        <template slot-scope="scope">
          <span>{{ translateServiceId(scope.row.serviceId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="命令ID" align="center" prop="commandId" />
      <el-table-column label="命令请求内容" align="center" prop="commandRequest"  show-overflow-tooltip/>
      <el-table-column label="命令响应内容" align="center" prop="commandResponse"  show-overflow-tooltip/>
      <el-table-column label="下达状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_commands_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['link:commands:edit']"
            v-if="scope.row.status == 1"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleDistribute(scope.row)"
          >下达命令
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCopy(scope.row)"
            v-hasPermi="['iot:devicecommands:edit']"
          >复制</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:devicecommands:edit']"
            v-if="scope.row.status == 1"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:devicecommands:remove']"
            v-if="scope.row.status == 1"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备动作对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备标识" prop="deviceIdentification">
          <el-input v-model="form.deviceIdentification" disabled placeholder="请输入设备标识"/>
        </el-form-item>
        <el-form-item label="服务名称" prop="serviceId">
          <el-select v-model="form.serviceId" clearable placeholder="请选择服务名称" size="small" @change="changeService">
            <el-option v-for="dict in servicesList" :key="dict.id" :label="dict.serviceName" :value="dict.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="命令名称" prop="commandId">
          <el-select v-model="form.commandId" clearable placeholder="请选择命令名称" size="small">
            <el-option v-for="dict in cdsList" :key="dict.id" :label="dict.name" :value="dict.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="命令内容" prop="commandRequest">
          <el-button size="medium" style="margin: 10px 0 10px 0" type="primary" @click="decoration">
            格式化
          </el-button>
          <el-input v-model="form.commandRequest" type="textarea" style="width:100%" :autosize="{ minRows: 5 }" resize="none" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" size="small">
            <el-option v-for="dict in dict.type.device_commands_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 下达设备命令对话框 -->
    <el-dialog :title="distributeTitle" :visible.sync="distributeOpen" append-to-body width="500px">
      <el-form ref="distributeForm" :model="distributeForm" :rules="distributeRules" label-width="80px">
        <el-form-item label="QoS等级" prop="qos">
          <el-select v-model="distributeForm.qos" placeholder="请选择QoS等级">
            <el-option label="QoS0 至多一次" value="0" />
            <el-option label="QoS1 至少一次" value="1" />
            <el-option label="QoS2 确保只有一次" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否保留" prop="retain">
          <el-select disabled v-model="distributeForm.retain" placeholder="是否保留消息">
            <el-option label="否" value="false" />
            <el-option label="是" value="true" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDistributeForm">发 送</el-button>
        <el-button @click="cancelDistribute">重 置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCommands, getCommands, delCommands, addCommands, updateCommands, distributeCommand } from "@/api/iot/device-commands";
import { queryProductServices } from "@/api/iot/services";
import { queryProductCommands } from "@/api/iot/commands";

export default {
  name: "Commands",
  props: ["deviceIdentification"],
  dicts: ["device_commands_status"],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备动作表格数据
      commandsList: [],
      // 设备服务表格数据
      servicesList: [],
      // 设备服务命令表格数据
      cdsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceIdentification: undefined,
        serviceId: undefined,
        commandId: undefined,
        commandRequest: undefined,
        commandResponse: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceIdentification: [
          { required: true, message: "设备标识不能为空", trigger: "blur" }
        ],
        serviceId: [
          { required: true, message: "服务ID不能为空", trigger: "change" }
        ],
        commandId: [
          { required: true, message: "命令ID不能为空", trigger: "change" }
        ],
        commandRequest: [
          { required: true, message: "命令请求内容不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "下达状态不能为空", trigger: "change" }
        ]
      },
      distributeTitle: "",
      // 是否显示弹出层
      distributeOpen: false,
      // 表单参数
      distributeForm: {},
      // 表单校验
      distributeRules: {}
    };
  },
  watch: {
    deviceIdentification(newval, oldval) {
      if (newval !== oldval) {
        this.queryParams.deviceIdentification = this.deviceIdentification;
        this.getList();
        queryProductServices(this.deviceIdentification).then(response => {
          this.servicesList = response.data;
        });
      }
    }
  },
  created() {
    if (this.deviceIdentification){
      this.queryParams.deviceIdentification = this.deviceIdentification;
    }
    this.getList();
  },
  methods: {
    /** 查询设备动作列表 */
    getList() {
      this.loading = true;
      listCommands(this.queryParams).then(response => {
        this.commandsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deviceIdentification: undefined,
        serviceId: undefined,
        commandId: undefined,
        commandRequest: undefined,
        commandResponse: undefined,
        status: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    changeService(newVal){
      queryProductCommands(newVal).then(response => {
        this.cdsList = response.data;
      });
    },
    translateServiceId(serviceId){
      let serviceName = "";
      for (let i = 0; i <this.servicesList.length ; i++) {
        if (this.servicesList[i].id == serviceId) {
          serviceName = this.servicesList[i].serviceName;
          break;
        }
      }
      return serviceName;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.deviceIdentification = this.deviceIdentification;
      this.form.status = "1";
      this.open = true;
      this.title = "添加设备动作";
    },
    handleCopy(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCommands(id).then(response => {
        this.loading = false;
        this.form = response.data;
        queryProductCommands(response.data.serviceId).then(commandResponse => {
          this.cdsList = commandResponse.data;
        });
        this.form.id = null;
        this.form.commandResponse = null;
        this.form.status = "1";
        this.open = true;
        this.title = "复制设备动作";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCommands(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改设备动作";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateCommands(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCommands(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备动作编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCommands(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/commands/export', {
        ...this.queryParams
      }, `commands_${new Date().getTime()}.xlsx`)
    },
    // 取消按钮
    cancelDistribute() {
      this.distributeOpen = false;
      this.resetDistribute();
    },
    // 表单重置
    resetDistribute() {
      this.distributeForm = {
        id: null,
        deviceIdentification: null,
        qos: null,
        retain: "false"
      };
      this.resetForm("distributeForm");
    },
    handleDistribute(row){
      const id = row.id || this.ids;
      this.resetDistribute();
      this.distributeForm.id = id;
      this.distributeForm.deviceIdentification = row.deviceIdentification;
      this.distributeOpen = true;
      this.distributeTitle = "下发设备动作数据";
    },
    submitDistributeForm(){
      const form = this.distributeForm;
      this.$modal.confirm('是否确认下发设备动作数据编号为"' + this.distributeForm.id + '"的数据项？').then(function () {
        return distributeCommand(form);
      }).then(() => {
        this.$modal.msgSuccess("下发成功");
        this.getList();
      }).catch(() => {
      }).finally(() => {
        this.distributeOpen = false;
      });
    },
    //验证json并格式化
    decoration() {
      if (this.isJSON(this.form.commandRequest)) {
        const jdata = JSON.stringify(
          JSON.parse(this.form.commandRequest),
          null,
          4
        );
        this.form.commandRequest = jdata;
      } else {
        this.$toast.fail("不是正确的json格式");
      }
    },
    isJSON(str) {
      if (typeof str === "string") {
        try {
          var obj = JSON.parse(str);
          if (typeof obj === "object" && obj) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          this.$toast.fail("不是json");
          return false;
        }
      }
    },
  }
};
</script>
